#include "ConfigDialog.h"
#include "ui_ConfigDialog.h"

#include <QDir>
#include <QDebug>

#include "core/global.h"

ConfigDialog::ConfigDialog(QWidget *parent) :
    QDialog(parent),
    ui(new Ui::ConfigDialog)
{
    ui->setupUi(this);

    loadConfig();
}

ConfigDialog::~ConfigDialog()
{
    delete ui;
}

void ConfigDialog::showEvent(QShowEvent *){
    loadConfig();
}

void ConfigDialog::loadConfig(){   
    ui->ruleOdd->setChecked(Config.value("game/ruleOdd").toBool());
    ui->ruleEven->setChecked(Config.value("game/ruleEven").toBool());

    ui->serverName->setText(Config.value("game/serverName").toString());
    ui->serverPort->setText(Config.value("game/serverPort").toString());
    ui->playerNum->setValue(Config.value("game/playerNum").toInt());
    ui->timeout->setValue(Config.value("game/timeout").toInt());
    ui->broadcastPort->setText(Config.value("game/broadcastPort").toString());

    const int item_num = ui->language->count();
    for(int index = 0; index < item_num; index++){
        if(ui->language->itemText(index) == Config.value("window/language").toString()){
            ui->language->setCurrentIndex(index);
        }
    }
}

void ConfigDialog::saveConfig(){
    Config.setValue("game/ruleOdd", ui->ruleOdd->isChecked());
    Config.setValue("game/ruleEven", ui->ruleEven->isChecked());

    Config.setValue("game/serverName", ui->serverName->text());
    Config.setValue("game/serverPort", ui->serverPort->text());
    Config.setValue("game/playerNum", ui->playerNum->value());
    Config.setValue("game/timeout", ui->timeout->value());
    Config.setValue("game/broadcastPort", ui->broadcastPort->text());

    Config.setValue("window/language", ui->language->currentText());
}

void ConfigDialog::on_buttonBox_accepted(){
    saveConfig();
}
